﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace ATCAssistant.StationBuilder
{
    public partial class MainForm : Form
    {
        private string lastSavePath = String.Empty;

        public MainForm()
        {
            InitializeComponent();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.ResetForm();
                this.LoadFile(dlg.FileName);
            }
        }

        private void LoadFile(string path)
        {
            XElement root = XElement.Load(path);
            this.LoadStationInfo(root);
            this.LoadRunways(root);
            this.LoadComms(root);
            this.LoadRestrictions(root);
        }
        private void LoadStationInfo(XElement root)
        {
            txtId.Text = root.Attribute("id").Value;
            txtName.Text = root.Element("name").Value;
        }
        private void LoadRunways(XElement root)
        {
            gridRunways.Rows.Clear();
            IEnumerable<XElement> runways = from rwy in root.Descendants("runway") select rwy;
            foreach (XElement rwyElement in runways)
            {
                object[] values = { rwyElement.Element("id").Value,
                                    rwyElement.Element("heading").Value,
                                    rwyElement.Element("length").Value,
                                    rwyElement.Element("width").Value
                                  };
                gridRunways.Rows.Add(values);
            }
        }
        private void LoadComms(XElement root)
        {
            gridComms.Rows.Clear();
            IEnumerable<XElement> comms = from comm in root.Descendants("frequency") select comm;
            foreach (XElement freqElement in comms)
            {
                object[] values = { freqElement.Attribute("position").Value,
                                    freqElement.Attribute("callsign").Value,
                                    freqElement.Value
                                  };
                gridComms.Rows.Add(values);
            }
        }
        private void LoadRestrictions(XElement root)
        {
            gridRestrictions.Rows.Clear();
            IEnumerable<XElement> restrictions = from rest in root.Descendants("restriction") select rest;
            foreach (XElement restElement in restrictions)
            {
                object[] values = { restElement.Element("runwayId").Value,
                                    restElement.Element("type").Value,
                                    restElement.Element("status").Value,
                                    restElement.Element("operation").Value,
                                    restElement.Element("start").Value,
                                    restElement.Element("stop").Value
                                  };
                gridRestrictions.Rows.Add(values);
            }
        }

        private void SaveFile(string path)
        {
            List<XElement> runways = this.SaveRunways();
            List<XElement> comms = this.SaveCommunications();
            List<XElement> rests = this.SaveRestrictions();

            // Generate the document
            XElement station =
                new XElement("station",
                    new XElement("name", txtName.Text),
                    new XElement("communications", comms),
                    new XElement("runways", runways),
                    new XElement("restrictions", rests),
                    new XAttribute("id", txtId.Text));
            station.Save(path);
        }
        private List<XElement> SaveRunways()
        {
            List<XElement> runways = new List<XElement>();
            foreach (DataGridViewRow row in gridRunways.Rows)
            {
                // Skip rows with no Runway identifier
                if (row.Cells["colId"].Value == null)
                    continue;

                XElement runway =
                    new XElement("runway",
                        new XElement("id", row.Cells["colId"].Value),
                        new XElement("heading", row.Cells["colHeading"].Value),
                        new XElement("length", row.Cells["colLength"].Value),
                        new XElement("width", row.Cells["colWidth"].Value));
                runways.Add(runway);
            }
            return runways;
        }
        private List<XElement> SaveCommunications()
        {
            List<XElement> comms = new List<XElement>();
            foreach (DataGridViewRow row in gridComms.Rows)
            {
                // Skip rows with no Runway identifier
                if (row.Cells["colFreq"].Value == null)
                    continue;

                XElement freq =
                    new XElement("frequency",
                        new XAttribute("position", row.Cells["colPositionType"].Value),
                        new XAttribute("callsign", row.Cells["colCallsign"].Value),
                        row.Cells["colFreq"].Value);
                comms.Add(freq);
            }
            return comms;
        }
        private List<XElement> SaveRestrictions()
        {
            List<XElement> restrictions = new List<XElement>();
            foreach (DataGridViewRow row in gridRestrictions.Rows)
            {
                // Skip rows with no Runway identifier
                if (row.Cells["colRwyID"].Value == null)
                    continue;

                XElement restriction =
                    new XElement("restriction",
                        new XElement("runwayId", row.Cells["colRwyID"].Value),
                        new XElement("type", row.Cells["colType"].Value),
                        new XElement("status", row.Cells["colRwyStatus"].Value),
                        new XElement("operation", row.Cells["colRestrictedOperation"].Value),
                        new XElement("start", row.Cells["colStartTime"].Value),
                        new XElement("stop", row.Cells["colStopTime"].Value));
                restrictions.Add(restriction);
            }
            return restrictions;
        }


        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(lastSavePath))
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.FileName = String.Format("{0}.xml", txtId.Text.ToLowerInvariant());
                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    lastSavePath = dlg.FileName;
                }
            }

            if (!String.IsNullOrEmpty(lastSavePath))
                this.SaveFile(lastSavePath);
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.ResetForm();
        }

        private void ResetForm()
        {
            lastSavePath = String.Empty;
            txtId.Clear();
            txtName.Clear();
            gridRunways.Rows.Clear();
            gridComms.Rows.Clear();
            gridRestrictions.Rows.Clear();
        }
    }
}
